import * as THREE from 'three';
import { VRButton } from 'three/examples/jsm/webxr/VRButton';

export const initVRScene = async (container) => {
  try {
    // 检查WebXR支持
    if (!navigator.xr) {
      throw new Error('WebXR not available');
    }

    const supported = await navigator.xr.isSessionSupported('immersive-vr');
    if (!supported) {
      throw new Error('VR not supported');
    }

    // 创建场景
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x87ceeb); // 天空蓝
    
    // 创建相机
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.set(0, 1.6, 3);
    
    // 创建渲染器
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.xr.enabled = true;
    renderer.shadowMap.enabled = true;
    container.appendChild(renderer.domElement);
    
    // 添加VR按钮
    document.body.appendChild(VRButton.createButton(renderer));
    
    // 添加光源
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
    scene.add(ambientLight);
    
    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
    directionalLight.position.set(0, 10, 0);
    directionalLight.castShadow = true;
    scene.add(directionalLight);
    
    // 创建地面
    const groundGeometry = new THREE.PlaneGeometry(50, 50);
    const groundMaterial = new THREE.MeshStandardMaterial({ 
      color: 0x808080,
      roughness: 0.8,
      metalness: 0.2
    });
    const ground = new THREE.Mesh(groundGeometry, groundMaterial);
    ground.rotation.x = -Math.PI / 2;
    ground.receiveShadow = true;
    scene.add(ground);

    // 添加环境物体
    const objects = await createEnvironment(scene);
    
    // 动画循环
    let controls = null;
    
    renderer.setAnimationLoop(() => {
      // 更新控制器
      if (controls) {
        controls.update();
      }
      renderer.render(scene, camera);
    });
    
    // 处理窗口大小变化
    const handleResize = () => {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    };
    
    window.addEventListener('resize', handleResize);
    
    return {
      cleanupScene: () => {
        window.removeEventListener('resize', handleResize);
        renderer.setAnimationLoop(null);
        renderer.dispose();
        container.removeChild(renderer.domElement);
      },
      sceneObjects: {
        scene,
        camera,
        renderer,
        objects,
        setControls: (newControls) => {
          controls = newControls;
        }
      }
    };
  } catch (error) {
    console.error('VR初始化失败:', error);
    throw error;
  }
};

async function createEnvironment(scene) {
  const objects = [];

  // 创建一些基础3D物体
  const geometry = new THREE.BoxGeometry(1, 1, 1);
  const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
  
  // 添加一些立方体作为示例
  for (let i = 0; i < 5; i++) {
    const cube = new THREE.Mesh(geometry, material);
    cube.position.set(
      Math.random() * 10 - 5,
      0.5,
      Math.random() * 10 - 5
    );
    cube.castShadow = true;
    scene.add(cube);
    objects.push(cube);
  }

  return objects;
} 